package org.weed.remote.ui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.nio.channels.ClosedByInterruptException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import org.weed.remote.network.RemoteServer;
import org.weed.remote.service.ConsoleService;

public class ServerConsole extends JFrame implements ActionListener {
	private static final long serialVersionUID = -623189625119593402L;
	private ExecutorService executor;
	private RemoteServer remoteServer;
	private boolean isPowerOn; 
	private JButton powerButton;
	private JTextArea console;
	
	public ServerConsole() {
		// Server		
		this.isPowerOn = false;
		
		// UI
		this.assembleUI();
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLocationRelativeTo(null);
		this.setTitle("Remote Console");
		this.setSize(300, 300);
		
	}
	
	private void assembleUI() {
		powerButton = new JButton("Start");
		powerButton.addActionListener(this);
		console = new JTextArea();
		
		JPanel panel = new JPanel();
		panel.add(powerButton);
		
		getContentPane().add(console, BorderLayout.CENTER);
		getContentPane().add(panel,BorderLayout.SOUTH);
	}
	
	public void actionPerformed(ActionEvent event)	{
		if (isPowerOn) {			
			powerOff();
			powerButton.setText("Start");
		} else {			
			powerOn();
			powerButton.setText("Stop");
		}
	}
	
	public void powerOn() {
		executor = Executors.newSingleThreadExecutor();
		try {
			remoteServer = new RemoteServer(8888, new ConsoleService(console));
			executor.execute(remoteServer);
			isPowerOn = true;
		} catch (Exception e) {
			
		}
	}
	
	public void powerOff() {
		try {
			remoteServer.terminate();
			executor.shutdownNow();
			executor.awaitTermination(1, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}		
		isPowerOn = false;
	}
	
	public static void main(String[] args) {
		ServerConsole serverConsole = new ServerConsole();
		serverConsole.setVisible(true);
	}
}
